package yun.common.http.response;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;

public class ErrorResponse implements IResponse {
	public static final int SOCKET_TIME_OUT = -1;
	public static final int CONNECT_TIME_OUT = -2;
	public static final int UNKNOWN_HOST = -3;
	public static final int UNMATCHED_CONTENT_TYPE = -7;
	public static final int NOT_FOUND_RESPONSE = -8;
	public static final int OFF_LINE = -10;
	public static final int HTTP_NG = -11;
	public static final int UNKNOWN = -99;

	private int mCode;
	private String mMessage;

	public ErrorResponse(int code, String message) {
		mCode = code;
		mMessage = message;
	}

	public ErrorResponse(int code) {
		this(code, messageOf(code));
	}

	public ErrorResponse(int code, Exception e) {
		this(code, messageOf(e));
	}

	public ErrorResponse() {
		this(0);
	}

	public int getCode() {
		return mCode;
	}

	public void setCode(int code) {
		mCode = code;
	}

	public void setMessage(String message) {
		mMessage = message;
	}

	public String getMessage() {
		return mMessage;
	}

	@Override
	public String toString() {
		StringBuilder toString = new StringBuilder();
		toString.append("+--<ErrorResponse>---").append('\n');
		toString.append("| ").append("code").append("   =").append(mCode).append('\n');
		toString.append("| ").append("message").append('=').append(mMessage).append('\n');
		toString.append("+--------------------").append('\n');
		return toString.toString();
	}

	private static final String messageOf(int code) {
		switch (code) {
		case SOCKET_TIME_OUT:
			return "SOCKET_TIME_OUT";
		case CONNECT_TIME_OUT:
			return "CONNECT_TIME_OUT";
		case UNKNOWN_HOST:
			return "UNKNOWN_HOST";
		case UNMATCHED_CONTENT_TYPE:
			return "UNMATCHED_CONTENT_TYPE";
		case NOT_FOUND_RESPONSE:
			return "NOT_FOUND_RESPONSE";
		case OFF_LINE:
			return "OFF_LINE";
		case HTTP_NG:
			return "HTTP_NG";
		case UNKNOWN:
		default:
			return "UNKNOWN";
		}
	}

	private static final String messageOf(Exception e) {
		String message = null;
		if (e != null) {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			PrintWriter pw = new PrintWriter(out);
			e.printStackTrace(pw);
			pw.flush();
			message = out.toString();
		}
		return message;
	}
}
